package cn.chencaiju.day13;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server2 {
	public static void main(String[] args) {
		ServerSocket server=null;
		Socket socket=null;
		try {
			//1024以上端口
			server=new ServerSocket(6666);
			System.out.println("等待连接！");
			//一直等待客户端连接
			socket=server.accept();
			System.out.println("新的连接。。。");
			
			//开始通信
			Thread t=new Thread(new ClientThread2(socket));
			t.start();
//			t.join();			
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			Utils.closeQuietly(server);
		}
	}
}
//异步线程,宏观上同步通信
class ClientThread2 implements Runnable{
	private DataInputStream in;
	private Socket socket;
	
	public ClientThread2(Socket socket) {
		super();
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			in=new DataInputStream(
					new BufferedInputStream(socket.getInputStream()));
			while(true) {
				String str=in.readUTF();
				System.out.println(str);
				if(str.equals("88"))break;
			}				
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			Utils.closeQuietly(in);
			Utils.closeQuietly(socket);
		}
		System.out.println("通信结束。。。。");
	}
	
}
